package com.ambimmort.shj.service.dpi.users.group;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.bean.Dpiusergroup;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;

/**
 * Created by zyt on 2015/7/31.
 */
@Service
public class Dpi_Users_GroupService {
    @Autowired
    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    /**
     *
     * @param groupNames
     * @param instanceNames
     * @throws Throwable
     */
    public void groupCreate(String groupNames,String instanceNames) throws Throwable{
        String groupName = new String(Base64.decodeBase64(groupNames),"utf-8") ;
        String instanceName =  new String(Base64.decodeBase64(instanceNames),"utf-8") ;

        init();
        try{
            String sql="insert into Dpiusergroup(name,instanceName)values(?,?)";
            Object[] param ={groupName,instanceName};
            baseDao.executeUpdate(sql,param);

//        Session session = hibernateSessionFactory.openSession();
//        Transaction tx = session.beginTransaction();
//        try {
//            Dpiusergroup bean = new Dpiusergroup();
//            bean.setInstanceName(instanceName);
//            bean.setName(groupName);
//            session.save(bean);
//            tx.commit();
//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }

    }


    public void groupDelete(String groupId) throws Throwable{
        init();
        try{
            String sq = "delete from Dpiusergroup where id=" + groupId;
            Object[] param = {};
            baseDao.executeUpdate(sq, param);

//        Session session = hibernateSessionFactory.openSession();
//        Dpiusergroup bean = (Dpiusergroup)session.get(Dpiusergroup.class,Integer.parseInt(groupId));
//        Transaction tx = session.beginTransaction();
//        try {
//            session.delete(bean);
//            tx.commit();
//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }


    }


    /**
     *
     * @param iDisplayStart 起始索引
     * @param iDisplayLength 索引条数
     * @param instanceNames
     * @return
     * @throws Throwable
     */
    public String listGroup( String iDisplayStart,String iDisplayLength,String instanceNames) throws Throwable{
        String instanceName = new String(Base64.decodeBase64(instanceNames),"utf-8") ;
        System.out.println("instanceName="+instanceName);

        init();
        try{
            JSONObject json = new JSONObject();
            JSONArray result = new JSONArray();
            Object[] param ={instanceName};
            rs=baseDao.executeSQL("select * from Dpiusergroup  where instanceName =?",param);

            while (rs.next()){
                JSONArray one = new JSONArray();
                one.add(rs.getInt("id"));
                one.add(rs.getString("name"));

                result.add(one);
            }
            json.put("aaData", result);

//        Session session = hibernateSessionFactory.openSession();
//        try {
//            Dpiusergroup bean = null;
//            Query q = session.createQuery("SELECT group FROM Dpiusergroup AS group where group.instanceName=:instanceName");
//            q.setParameter("instanceName", instanceName);
//            q.setMaxResults(Integer.parseInt(iDisplayLength));
//            q.setFirstResult(Integer.parseInt(iDisplayStart));
//
//            java.util.List<Dpiusergroup> l = q.list();
//            JSONObject json = new JSONObject();
//            JSONArray result = new JSONArray();
//            Query countQuery = session.createQuery("SELECT count(*) FROM Dpiusergroup where instanceName=:in");
//            countQuery.setParameter("in", instanceName);
//            int length = ((Long) countQuery.iterate().next()).intValue();
//
//            json.put("iTotalRecords", length);
//            json.put("iTotalDisplayRecords", length);
//            int end = Integer.parseInt(iDisplayStart) + Integer.parseInt(iDisplayLength);
//            if (end > length) {
//                end = length;
//            }
//            for (int i = 0; i < l.size(); i++) {
//                bean = (Dpiusergroup) l.get(i);
//                JSONArray one = new JSONArray();
//                one.add(bean.getId());
//                one.add(bean.getName());
//
//                result.add(one);
//            }
//            json.put("aaData", result);

            try {
                return json.toString();
            } catch (Exception e) {
                return "[]";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return"[]";
        } finally {
            close();
//            session.close();
        }


    }


    public void groupUpdate(String groupId,String groupName) throws Throwable{
        init();
        try{
            String sq = "update Dpiusergroup set id=" + groupId+" where name='"+groupName+"'";
            Object[] param = {};
            baseDao.executeUpdate(sq, param);

//        Session session = hibernateSessionFactory.openSession();
//        Dpiusergroup bean = (Dpiusergroup) session.get(Dpiusergroup.class, Integer.parseInt(groupId));
//        Transaction tx = session.beginTransaction();
//        try {
//            bean.setName(groupName);
//            session.update(bean);
//            tx.commit();
//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }

    }
}
